//
//  FCRelationListViewController.m
//  customerRelation_Example
//
//  Created by 陈文斌 on 2019/2/15.
//  Copyright © 2019 64912907. All rights reserved.
//

#import "FCRelationListViewController.h"
#import "MJRefresh.h"
#import "FCRelationTableViewCell.h"
#import "FCCustomerRelationRequest.h"
#import "FCRelationListModel.h"
#import "FCRelationCompanyDetailViewController.h"
#import "FCRelationBindRequestViewController.h"
#import "CustomerRelationHeader.h"
#import "saveSandBox.h"

@interface FCRelationListViewController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *relationRequestsArr;
@property (nonatomic, assign) BOOL isSelect;

@end

@implementation FCRelationListViewController

- (NSMutableArray<FCRelationModel *> *)relationRequestsArr{
    if (!_relationRequestsArr) {
        _relationRequestsArr = [NSMutableArray array];
    }
    return _relationRequestsArr;
}

- (void)setupUI{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.and.bottom.and.right.mas_equalTo(0);
    }];
    [self setupTableView];
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
}

- (void)setupNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updataData) name:CrmSupplyRelationChanged object:nil];
}

- (void)updataData{
    [self loadNewData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupData];
    [self setupUI];
    [self setupNotification];
}

- (void)setupData{
    [self.tableView.mj_footer endRefreshing];
    self.relationRequestsArr = [saveSandBox getDataBaseWithClass:[FCRelationModel class] andLimitType:[NSString stringWithFormat:@"type='%@'", self.relationType.Id]];
    if (self.relationRequestsArr.count < 1) {
        [self loadNewData];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.tableView.mj_footer endRefreshing];
//    self.relationRequestsArr = [saveSandBox getDataBaseWithClass:[FCRelationModel class] andLimitType:[NSString stringWithFormat:@"type='%@'", self.relationType.Id]];
//    if (self.relationRequestsArr.count < 1) {
//        [self loadNewData];
//    }
}

#pragma mark - tableView

#define RelationCell @"FCRelationTableViewCell"

- (void)setupTableView{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = FCBackColor;
    self.tableView.separatorStyle = UITableViewCellEditingStyleNone;
    [self setExtraCellLineHidden:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([FCRelationTableViewCell class]) bundle:nil] forCellReuseIdentifier:RelationCell];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.stateLabel.hidden = YES;
    footer.refreshingTitleHidden = YES;
    footer.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.automaticallyHidden = YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.relationRequestsArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return IphonePlus ? 54 : 48;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FCRelationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RelationCell forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    FCRelationModel *relationRequest = self.relationRequestsArr[indexPath.row];
    NSString *companyNameStr = relationRequest.rel.BrandName ?: relationRequest.relCompanyName;
    cell.companyName.text = companyNameStr;
    
    
    [cell setContactNumberWithNumber:relationRequest.relRelation.emps.count];
    [cell setStatusStyleWithStatus:relationRequest.status];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
        if (!self.isSelect) {
            self.isSelect = YES;
            FCRelationModel *relationRequestModel = self.relationRequestsArr[indexPath.row];
            NSDictionary *args = @{
                                   @"id": relationRequestModel.Id,
                                   @"companyId": relationRequestModel.relId
                                   };
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];
//            [SVProgressHUD show];
            WJCWeakSelf
            [FCCustomerRelationRequest getRelationDetailWithArgs:args success:^(id resultObj) {
                FCRelationModel *relationModel = [FCRelationModel mj_objectWithKeyValues:resultObj[@"data"][@"crmSupplyRelationGet"]];
                FCRelationCompanyDetailViewController *relationBindRequestVC = [[FCRelationCompanyDetailViewController alloc] init];
                relationBindRequestVC.relation = relationModel;
                [weakSelf.navigationController pushViewController:relationBindRequestVC animated:YES];
                [SVProgressHUD dismiss];
                weakSelf.isSelect = NO;
            } failure:^(NSError *error) {
                [SVProgressHUD dismiss];
                weakSelf.isSelect = NO;
            }];
        }
    
    
}

- (void)setExtraCellLineHidden: (UITableView *)tableView{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor whiteColor];
    [tableView setTableFooterView:view];
}

#pragma mark - 数据加载
-(void)loadNewData{
    NSDictionary *args = @{@"skip": @(0),
                           @"take": @(20),
                           @"model": @(true),
                           @"orderBy": @"status_asc",
                           @"typeId": self.relationType.Id};
    WJCWeakSelf
    [FCCustomerRelationRequest getRelationRequestsWithArgs:args success:^(NSDictionary *resultObj) {
        FCRelationListModel *body = [FCRelationListModel mj_objectWithKeyValues: resultObj[@"data"][@"crmSupplyRelations"]];
        [weakSelf.relationRequestsArr removeAllObjects];
        MJRefreshAutoNormalFooter *footer = weakSelf.tableView.mj_footer;
        [weakSelf.relationRequestsArr addObjectsFromArray:body.items];
        [saveSandBox DELETEDataWithType:nil andOther:nil andClass:[FCRelationModel class]];
        for (FCRelationModel *relation in body.items) {
            [saveSandBox saveDataBaseClass:[FCRelationModel class] andObject:relation orType:self.relationType.Id andOther:nil];
        }
        
        [weakSelf.tableView.mj_header endRefreshing];
        if(weakSelf.relationRequestsArr.count == body.pageInfo.total){
            weakSelf.tableView.mj_footer.endRefreshingWithNoMoreData;
        } else{
            [weakSelf.tableView.mj_footer resetNoMoreData];
        }
        [weakSelf.tableView reloadData];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}
-(void)loadMoreData{
    NSDictionary *args = @{@"skip": @(self.relationRequestsArr.count),
                           @"take": @(20),
                           @"model": @(1),
                           @"orderBy": @"status_asc",
                           @"typeId": self.relationType.Id};
    WJCWeakSelf
    [FCCustomerRelationRequest getRelationRequestsWithArgs:args success:^(NSDictionary *resultObj) {
        FCRelationListModel *body = [FCRelationListModel mj_objectWithKeyValues: resultObj[@"data"][@"crmSupplyRelations"]];
        [weakSelf.relationRequestsArr addObjectsFromArray:body.items];
        for (FCRelationModel *relation in body.items) {
            [saveSandBox saveDataBaseClass:[FCRelationModel class] andObject:relation orType:self.relationType.Id andOther:nil];
        }
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.mj_footer endRefreshing];
        if(weakSelf.relationRequestsArr.count == body.pageInfo.total){
            weakSelf.tableView.mj_footer.endRefreshingWithNoMoreData;
            MJRefreshAutoNormalFooter *footer = weakSelf.tableView.mj_footer;
            return ;
        }
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
